const SCOPES = ['snsapi_base', 'snsapi_userinfo']
const defaultPwd = 'etsdfg4252'

import {openIDApi,loginApiApp,wechatRegisterApi} from '../api/api';
import store from '../store/index'
import cookies from './cookies'
import {key_userLoginUser} from './cookieskey'
import utils from './utils'

export default {
    getOpenID:function(vuethis,wechatcode){
        let _this = this;
        // 传递过来的vue
        let _vuethis = vuethis;
        // 从cookies中获取Ready中保存的请求的url
        let ready_url = JSON.parse(cookies.getCookie('Ready'));
        let companyCode = utils.getCompanyCode(ready_url);
        if (companyCode){
            // 请求获取用户openID使用的参数
            let apiParams = {
              "code":wechatcode,
              "companyCode":companyCode
            };
            // 从后台获取用户openid
            openIDApi(apiParams).then(data => {
              let {msg,code,content} = data;
              if (code !== 200){
                // 弹出请求错误信息
                _vuethis.$vux.toast.text("获取用户id出错！"+msg)
              }else{
                // 判断获取openid是否失败
                if(typeof(content.openid) !== "undefined"){
                  // 成功获取openid，登陆
                  _this.userLogin(_vuethis,content.openid,companyCode)
                }else{
                  // 获取openid失败，打印微信公众平台返回信息
                  _vuethis.$vux.toast.text(content)
                }
              }
            });
        }else{
          _vuethis.$vux.toast.text("firstpath url error")
        }
    },
    userLogin:function(vuethis,openid,companyCode){
        let _vuethis = vuethis;
        // 登陆请求参数
        let apiParms = {
          "username": openid,  //用户openid
          "password": defaultPwd ,   //用户密码，在这里和app不同，微信使用一个默认的密码来注册和登陆
          "companyCode":companyCode    //注册公司
        };
        //登陆普通用户
        loginApiApp(apiParms).then(data => {
          // 获取请求返回参数
          let { msg, code, content } = data;
          if (code !== 200) {   //是否登陆成功
              //用户不存在注册用户
              if(code === 2008){
                // 请求注册用户
                wechatRegisterApi(apiParms).then(data => {
                    let { msg, code, content } = data;
                    if (code !== 200) {
                        _vuethis.$vux.toast.text("注册出错！"+msg)
                    }else{
                       let url = JSON.parse(cookies.getCookie('Ready'));  //获取原始url
                       cookies.removeCookie('Ready');
                       window.location.href = url  //重新加载
                    }
                })
              }else{
                _vuethis.$vux.toast.text("登陆出错！"+msg)
              }
          } else {
            //登陆成功保存到cookies中
            cookies.setCookie(key_userLoginUser+companyCode, JSON.stringify(content), 25);
            let url = JSON.parse(cookies.getCookie('Ready'));//重载入保存的网页
            cookies.removeCookie('Ready');
            //重载入保存的网页
            window.location.href = url
          }
        });
    },
}

